package pers.chy.chyappointmentplatform.Service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import pers.chy.chyappointmentplatform.Mapper.HisMapper.V_YgxxMapper;
import pers.chy.chyappointmentplatform.Model.V_YgxxDTO;
import pers.chy.chyappointmentplatform.Model.NoMapping.UserDTO;
import pers.chy.chyappointmentplatform.Utils.ChyException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录注册服务
 */
@Service
public class LoginService {


    @Autowired
    private V_YgxxMapper v_ygxxMapper;

    /**
     * 登录：获取用户信息
     *
     * @param userName
     * @param password
     * @return
     * @throws Exception
     */
    public UserDTO doLogin(String userName, String password, long roleID) throws Exception {
        try {

            // 密码验证（MD5）
            String encryptPassword = DigestUtils.md5DigestAsHex((userName + password).getBytes()).toUpperCase(); //MD5加密
            List<V_YgxxDTO> v_ygxxDTOList = v_ygxxMapper.selectByYhdm(userName);
            if (v_ygxxDTOList.size() == 0) {
                throw new ChyException("用户不存在（请使用本院工号）");
            }
            if (v_ygxxDTOList.get(0).getYhmm().equals(encryptPassword) == false) {
                throw new ChyException("密码错误（请输入市一信息系统的密码）");
            }

            // 权限判断
            V_YgxxDTO v_ygxxDTO = v_ygxxDTOList.stream()  //实现查找，找到则返回匹配的对象，找不到则返回null
                    .filter(temp -> roleID == temp.getRoleID())
                    .findAny()
                    .orElse(null);
            if (v_ygxxDTO == null) {
                throw new ChyException("权限不足");
            }


            // 获取基本信息
            UserDTO userDTO = new UserDTO();
            userDTO.setYgxm(v_ygxxDTOList.get(0).getYgxm());
            userDTO.setYgdm(v_ygxxDTOList.get(0).getYgdm());
            userDTO.setKsdm(v_ygxxDTOList.get(0).getKsdm());
            userDTO.setKsmc(v_ygxxDTOList.get(0).getKsmc());
            userDTO.setYgzc(v_ygxxDTOList.get(0).getYgzc());
            List<Long> roleList = new ArrayList();
            for (V_YgxxDTO var : v_ygxxDTOList) {
                roleList.add(var.getRoleID());
            }
            userDTO.setRoleIdList(roleList);    // 角色ID列表

            //
            return userDTO;

        } catch (Exception ex) {
            throw ex;
        }


    }
}
